/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.component.spreadsheet.knowledge;

import cn.ac.nercis.pes.common.constant.evaluation.EvaluationConclusion;
import cn.ac.nercis.pes.common.constant.evaluation.EvaluationResult;
import cn.ac.nercis.pes.community.component.spreadsheet.TableSheetView;
import cn.ac.nercis.pes.community.model.vo.knowledge.KmEvaluationRecordVO;
import cn.ac.nercis.pes.community.support.event.EventCallback;
import cn.ac.nercis.pes.model.dto.common.ItemData;
import cn.ac.nercis.pes.model.dto.knowledge.KmSimpleTargetDTO;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.controlsfx.control.spreadsheet.GridBase;
import org.controlsfx.control.spreadsheet.SpreadsheetCell;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 风险分析信息（知识库）表控件
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class KmEvaluationRecordSheetView extends TableSheetView<KmEvaluationRecordVO> {
    private final static List<String> COLUMNS = List.of("测评指标","符合情况","D","A","K","结果记录");
    private final static Integer UNIT_COLUMN_INDEX = 0;
    private final static Integer CONCLUSION_COLUMN_INDEX = 1;
    private final static Integer D_RESULT_COLUMN_INDEX = 2;
    private final static Integer A_RESULT_COLUMN_INDEX = 3;
    private final static Integer K_RESULT_COLUMN_INDEX = 4;
    private final static Integer CONTENT_COLUMN_INDEX = 5;

    private final ObservableList<String> conclusionList;
    private final ObservableList<String> dResultList;
    private final ObservableList<String> akResultList;
    private final ObservableList<ItemData> unitTargetList;
    private EventCallback<Set<String>> onDeleteAction;

    public KmEvaluationRecordSheetView(){
        this.getStyleClass().add("pes-sheet-view");
        conclusionList = FXCollections.observableArrayList(EvaluationConclusion.findAllByManage()
                .stream()
                .map(EvaluationConclusion::getName).toList());
        var dList = Stream.of(EvaluationResult.MATCH,EvaluationResult.NOT_MATCH,EvaluationResult.NOT_APPLICABLE)
                .map(EvaluationResult::getName).toList();
        var akList = Stream.of(EvaluationResult.MATCH,EvaluationResult.NOT_MATCH)
                .map(EvaluationResult::getName).toList();
        dResultList = FXCollections.observableArrayList(dList);
        akResultList = FXCollections.observableArrayList(akList);
        unitTargetList = FXCollections.observableArrayList();

        var grid = new GridBase(DEFAULT_EMPTY_DATA_COUNT, COLUMNS.size());
        grid.getColumnHeaders().addAll(COLUMNS);
        buildGrid(grid,DEFAULT_EMPTY_DATA_COUNT);
        setGrid(grid);
        getColumns().get(UNIT_COLUMN_INDEX).setPrefWidth(200);
        getColumns().get(CONCLUSION_COLUMN_INDEX).setPrefWidth(130);
        getColumns().get(D_RESULT_COLUMN_INDEX).setPrefWidth(100);
        getColumns().get(A_RESULT_COLUMN_INDEX).setPrefWidth(100);
        getColumns().get(K_RESULT_COLUMN_INDEX).setPrefWidth(100);
        getColumns().get(CONTENT_COLUMN_INDEX).setPrefWidth(260);
        //this.setRequiredColumns();
    }

    public void initialize(EventCallback<Set<String>> deleteAction){
        this.onDeleteAction = deleteAction;
        this.editModel.set(false);
    }

    public void refreshUnitTargetData(List<KmSimpleTargetDTO> locationData){
        this.unitTargetList.clear();
        this.unitTargetList.addAll(locationData.stream().map(item->new ItemData(item.getName(),item.getId())).toList());
    }

    @Override
    protected void loadContent(KmEvaluationRecordVO info, Integer sheetRowIndex){
        this.checkAndAppendEmptyDataRow(sheetRowIndex);
        var unitName = this.unitTargetList.stream()
                .filter(ut-> StringUtils.equals(ut.getValue(),info.getUnitTargetId()))
                .map(ItemData::getName)
                .findFirst()
                .orElse(StringUtils.EMPTY);
        this.getGrid().getRows().get(sheetRowIndex).get(UNIT_COLUMN_INDEX).setItem(unitName);
        this.getGrid().getRows().get(sheetRowIndex).get(CONCLUSION_COLUMN_INDEX).setItem(info.getConclusion().getName());
        this.getGrid().getRows().get(sheetRowIndex).get(D_RESULT_COLUMN_INDEX).setItem(info.getdResult().getName());
        this.getGrid().getRows().get(sheetRowIndex).get(A_RESULT_COLUMN_INDEX).setItem(info.getaResult().getName());
        this.getGrid().getRows().get(sheetRowIndex).get(K_RESULT_COLUMN_INDEX).setItem(info.getkResult().getName());
        this.getGrid().getRows().get(sheetRowIndex).get(CONTENT_COLUMN_INDEX).setItem(info.getContent());
        info.resetChange();
    }

    public List<KmEvaluationRecordVO> getModifyData(){
        List<KmEvaluationRecordVO> data = new ArrayList<>();
        for(var sheetRowIndex=0;sheetRowIndex<this.getGrid().getRows().size();sheetRowIndex++){
            if(this.isEmptyData(sheetRowIndex)){
                continue;
            }
            data.add(getModifyData(sheetRowIndex));
        }
        return data.stream()
                .filter(item-> Objects.nonNull(item) && item.isChange())
                .collect(Collectors.toList());
    }

    private KmEvaluationRecordVO getModifyData(Integer sheetRowIndex){
        if (toDataIndex(sheetRowIndex) < 0) {
            return null;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        KmEvaluationRecordVO info;
        if (toDataIndex(sheetRowIndex) < this.sheetData.size()) {
            info = this.sheetData.get(toDataIndex(sheetRowIndex));
        } else {
            info = new KmEvaluationRecordVO();
        }
        var unitTargetName = StringUtils.trim(rowData.get(UNIT_COLUMN_INDEX).getText());
        var unitTargetId = this.unitTargetList.stream()
                .filter(ut->StringUtils.equals(ut.getName(),unitTargetName))
                .map(ItemData::getValue)
                .findFirst().orElse(StringUtils.EMPTY);
        info.setUnitTargetId(unitTargetId);
        info.setConclusion(EvaluationConclusion.fromName(rowData.get(CONCLUSION_COLUMN_INDEX).getText()));
        info.setdResult(EvaluationResult.fromName(rowData.get(D_RESULT_COLUMN_INDEX).getText()));
        info.setaResult(EvaluationResult.fromName(rowData.get(A_RESULT_COLUMN_INDEX).getText()));
        info.setkResult(EvaluationResult.fromName(rowData.get(K_RESULT_COLUMN_INDEX).getText()));
        info.setContent(StringUtils.trim(rowData.get(CONTENT_COLUMN_INDEX).getText()));
        return info;
    }

    @Override
    protected boolean validate(ObservableList<SpreadsheetCell> rowData){
        boolean validResult = true;
        if(StringUtils.isBlank(rowData.get(UNIT_COLUMN_INDEX).getText())){
            rowData.get(UNIT_COLUMN_INDEX).getStyleClass().add(REQUIRED_CELL_STYLE);
            validResult = false;
        }else{
            rowData.get(UNIT_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        }
        if(StringUtils.isBlank(rowData.get(CONCLUSION_COLUMN_INDEX).getText())){
            rowData.get(CONCLUSION_COLUMN_INDEX).getStyleClass().add(REQUIRED_CELL_STYLE);
            validResult = false;
        }else{
            rowData.get(CONCLUSION_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        }
        return validResult;
    }

    @Override
    protected void clearValidate(ObservableList<SpreadsheetCell> rowData) {
        rowData.get(UNIT_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
        rowData.get(CONCLUSION_COLUMN_INDEX).getStyleClass().remove(REQUIRED_CELL_STYLE);
    }

    @Override
    protected boolean isEmptyData(Integer sheetRowIndex){
        if(toDataIndex(sheetRowIndex) < 0){
            return true;
        } else if(toDataIndex(sheetRowIndex) < this.sheetData.size()){
            return false;
        }
        var rowData = this.getGrid().getRows().get(sheetRowIndex);
        return StringUtils.isBlank(rowData.get(UNIT_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(CONCLUSION_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(D_RESULT_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(A_RESULT_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(K_RESULT_COLUMN_INDEX).getText())
                && StringUtils.isBlank(rowData.get(CONTENT_COLUMN_INDEX).getText());
    }

    @Override
    protected ObservableList<SpreadsheetCell> generateEmptyDataRow(int dataIndex) {
        final ObservableList<SpreadsheetCell> data = FXCollections.observableArrayList();
        AtomicInteger columnIndex = new AtomicInteger(0);
        data.add(getComboBoxCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),unitTargetList));
        data.add(getComboBoxCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),conclusionList));
        data.add(getComboBoxCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),dResultList));
        data.add(getComboBoxCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),akResultList));
        data.add(getComboBoxCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),akResultList));
        data.add(getTextAreaCell(toSheetRowIndex(dataIndex),columnIndex.getAndIncrement(),"data-cell-left"));
        return data;
    }

    @Override
    protected void deleteData() {
        if(Objects.nonNull(this.onDeleteAction)){
            var selectIds= this.selectedSheetRowIndex()
                    .stream()
                    .filter(sheetRowIndex->toDataIndex(sheetRowIndex)>=0 && toDataIndex(sheetRowIndex)<this.sheetData.size())
                    .map(sheetRowIndex->this.sheetData.get(toDataIndex(sheetRowIndex)).getId())
                    .collect(Collectors.toSet());
            this.onDeleteAction.action(selectIds);
        }
    }

    @Override
    protected List<String> getDataColumns() {
        return COLUMNS;
    }

}